import sequelize from './db.config.js';
import User from '../models/User.js';
import FamilyTree from '../models/FamilyTree.js';
import Person from '../models/Person.js';
import PersonEvent from '../models/PersonEvent.js';
import PersonRelationship from '../models/PersonRelationship.js';
import Common from '../models/Common.js';

// --- 1. 定义模型关联 ---
User.hasMany(FamilyTree, { foreignKey: 'userId', as: 'familyTrees' });
FamilyTree.belongsTo(User, { foreignKey: 'userId', as: 'user' });
FamilyTree.hasMany(Person, { foreignKey: 'familyTreeId', as: 'members' });
Person.belongsTo(FamilyTree, { foreignKey: 'familyTreeId', as: 'familyTree' });
Person.hasMany(PersonEvent, { foreignKey: 'personId', as: 'events' });
PersonEvent.belongsTo(Person, { foreignKey: 'personId', as: 'person' });
Person.belongsToMany(Person, {
  as: 'Relations',
  through: PersonRelationship,
  foreignKey: 'personId1',
  otherKey: 'personId2'
});
Person.belongsToMany(Person, {
  as: 'RelatedTo',
  through: PersonRelationship,
  foreignKey: 'personId2',
  otherKey: 'personId1'
});
PersonEvent.belongsTo(Common, { foreignKey: 'eventTypeId', targetKey: 'itemId', as: 'eventType' });

// --- 2. 初始化数据库和数据填充 ---
export async function initializeDatabase() {
  try {
    console.log('开始同步模型...');
    await sequelize.sync({ force: true });
    console.log('✅ 模型同步完成');
    // --- 3. 填充共通表 (Common) ---
    const commonData = [
      { groupId: 1, groupName: '关系类型', itemId: 1, itemName: '父亲' },
      { groupId: 1, groupName: '关系类型', itemId: 2, itemName: '养父' },
      { groupId: 1, groupName: '关系类型', itemId: 3, itemName: '养母' },
      { groupId: 1, groupName: '关系类型', itemId: 4, itemName: '母亲' },
      { groupId: 1, groupName: '关系类型', itemId: 5, itemName: '妻子' },
      { groupId: 1, groupName: '关系类型', itemId: 6, itemName: '离异妻子' },
      { groupId: 1, groupName: '关系类型', itemId: 7, itemName: '未婚情人' },
      { groupId: 1, groupName: '关系类型', itemId: 8, itemName: '女儿' },
      { groupId: 1, groupName: '关系类型', itemId: 9, itemName: '儿子' },
      { groupId: 1, groupName: '关系类型', itemId: 10, itemName: '私生子' },
      { groupId: 1, groupName: '关系类型', itemId: 11, itemName: '私生女' },
      { groupId: 2, groupName: '事件类别', itemId: 1, itemName: '结婚' },
      { groupId: 2, groupName: '事件类别', itemId: 2, itemName: '晋升' },
      { groupId: 2, groupName: '事件类别', itemId: 3, itemName: '重病' },
      { groupId: 2, groupName: '事件类别', itemId: 4, itemName: '重要成果' },
      { groupId: 2, groupName: '事件类别', itemId: 5, itemName: '交通事故' },
      { groupId: 2, groupName: '事件类别', itemId: 6, itemName: '升学' },
    ];
    await Common.bulkCreate(commonData);
    console.log('✅ 共通表数据填充完成');
    // --- 4. 填充示例数据 ---
    console.log('开始填充丰富的示例数据...');
    const user1 = await User.create({ username: 'test_user', password: 'password123' });
    const familyTree1 = await FamilyTree.create({ userId: user1.id, name: '王氏家族', description: '一个庞大而复杂的家族示例' });
    console.log('-> 已创建用户和家谱');
    const p = {};
    const personsData = [
      { id: 1, name: '王老太爷', gender: '男', generation: 1, birthDate: '1920-01-01', occupation: '退休工人', education: '小学', address: '北京市朝阳区', maritalStatus: '已婚', photos: [{ url: '', description: '王老太爷年轻时的照片', uploadDate: '2024-01-15T10:30:00Z', fileName: 'wang_old_young.jpg' }] },
      { id: 2, name: '王老太太', gender: '女', generation: 1, birthDate: '1922-02-02', occupation: '退休教师', education: '初中', address: '北京市朝阳区', maritalStatus: '已婚', photos: [{ url: '', description: '王老太太与丈夫的合影', uploadDate: '2024-01-15T10:35:00Z', fileName: 'wang_old_couple.jpg' }] },
      { id: 3, name: '王大山', gender: '男', generation: 2, birthDate: '1945-03-03', occupation: '工程师', education: '大学', address: '上海市浦东新区', maritalStatus: '已婚' },
      { id: 4, name: '张秀英', gender: '女', generation: 2, birthDate: '1947-04-04', occupation: '会计', education: '大专', address: '上海市浦东新区', maritalStatus: '已婚' },
      { id: 5, name: '王大河', gender: '男', generation: 2, birthDate: '1948-05-05', occupation: '医生', education: '研究生', address: '广州市天河区', maritalStatus: '已婚' },
      { id: 6, name: '陈玉梅', gender: '女', generation: 2, birthDate: '1950-06-06', occupation: '护士', education: '中专', address: '广州市天河区', maritalStatus: '已婚' },
      { id: 7, name: '王建国', gender: '男', generation: 3, birthDate: '1970-07-07', occupation: '软件工程师', education: '本科', address: '深圳市南山区', maritalStatus: '已婚' },
      { id: 8, name: '李丽', gender: '女', generation: 3, birthDate: '1972-08-08', occupation: '设计师', education: '本科', address: '深圳市南山区', maritalStatus: '已婚' },
      { id: 9, name: '王建华', gender: '女', generation: 3, birthDate: '1973-09-09', occupation: '教师', education: '本科', address: '杭州市西湖区', maritalStatus: '已婚' },
      { id: 10, name: '赵强', gender: '男', generation: 3, birthDate: '1971-10-10', occupation: '销售经理', education: '大专', address: '杭州市西湖区', maritalStatus: '已婚' },
      { id: 12, name: '王秀兰', gender: '女', generation: 3, birthDate: '1978-12-12', occupation: '护士', education: '大专', address: '武汉市江汉区', maritalStatus: '已婚' },
      { id: 13, name: '张伟', gender: '男', generation: 3, birthDate: '1977-01-13', occupation: '医生', education: '研究生', address: '武汉市江汉区', maritalStatus: '已婚' },
      { id: 14, name: '王小明', gender: '男', generation: 4, birthDate: '1995-02-14', occupation: '程序员', education: '本科', address: '北京市海淀区', maritalStatus: '已婚' },
      { id: 15, name: '刘芳', gender: '女', generation: 4, birthDate: '1996-03-15', occupation: '产品经理', education: '本科', address: '北京市海淀区', maritalStatus: '已婚' },
      { id: 16, name: '王小红', gender: '女', generation: 4, birthDate: '1998-04-16', occupation: '学生', education: '在读研究生', address: '北京市海淀区', maritalStatus: '未婚' },
      { id: 17, name: '赵小东', gender: '男', generation: 4, birthDate: '1997-05-17', occupation: '金融分析师', education: '研究生', address: '上海市黄浦区', maritalStatus: '未婚' },
      { id: 18, name: '赵小花', gender: '女', generation: 4, birthDate: '2000-06-18', occupation: '学生', education: '在读本科', address: '上海市黄浦区', maritalStatus: '未婚' },
      { id: 19, name: '王小军', gender: '男', generation: 4, birthDate: '1999-07-19', occupation: '自由职业', education: '高中', address: '成都市武侯区', maritalStatus: '未婚' },
      { id: 20, name: '王小雅', gender: '女', generation: 4, birthDate: '2002-08-20', occupation: '学生', education: '在读本科', address: '武汉市洪山区', maritalStatus: '未婚' },
      { id: 21, name: '王小虎', gender: '男', generation: 3, birthDate: '1976-09-21', occupation: '企业家', education: '本科', address: '广州市越秀区', maritalStatus: '已婚' },
      { id: 22, name: '王宝宝', gender: '男', generation: 5, birthDate: '2022-10-22', occupation: '幼儿', education: '幼儿园', address: '北京市海淀区', maritalStatus: '未婚' },
    ];
    for (const personData of personsData) {
      p[personData.id] = await Person.create({ ...personData, familyTreeId: familyTree1.id });
    }
    console.log(`-> 已创建 ${personsData.length} 位家族成员`);
    const relationshipsData = [
      // 王老太爷和王老太太的所有子女
      { p1: 1, p2: 3, type: 1 }, { p1: 2, p2: 3, type: 4 },   // 王大山 亲生
      { p1: 1, p2: 5, type: 1 }, { p1: 2, p2: 5, type: 4 },   // 王大河 亲生
      { p1: 1, p2: 7, type: 1 }, { p1: 2, p2: 7, type: 4 },   // 王建国 亲生
      { p1: 1, p2: 9, type: 1 }, { p1: 2, p2: 9, type: 4 },   // 王建华 亲生
      { p1: 1, p2: 12, type: 2 }, { p1: 2, p2: 12, type: 3 }, // 王秀兰 养女
      // 夫妻关系
      { p1: 1, p2: 2, type: 5 },
      { p1: 3, p2: 4, type: 5 }, { p1: 5, p2: 6, type: 5 },
      { p1: 7, p2: 8, type: 5 }, { p1: 9, p2: 10, type: 5 },
      { p1: 12, p2: 13, type: 5 }, { p1: 14, p2: 15, type: 5 },
      // 子女关系（孙辈等）
      { p1: 3, p2: 7, type: 1 }, { p1: 4, p2: 7, type: 4 },
      { p1: 3, p2: 9, type: 1 }, { p1: 4, p2: 9, type: 4 },
      { p1: 3, p2: 12, type: 2 }, { p1: 4, p2: 12, type: 3 },
      { p1: 5, p2: 21, type: 1 }, { p1: 6, p2: 21, type: 4 },
      { p1: 7, p2: 14, type: 1 }, { p1: 8, p2: 14, type: 4 },
      { p1: 7, p2: 16, type: 1 }, { p1: 8, p2: 16, type: 4 },
      { p1: 10, p2: 17, type: 1 }, { p1: 9, p2: 17, type: 4 },
      { p1: 10, p2: 18, type: 1 }, { p1: 9, p2: 18, type: 4 },
      { p1: 11, p2: 19, type: 9 }, { p1: 12, p2: 19, type: 4 },
      { p1: 14, p2: 22, type: 1 }, { p1: 15, p2: 22, type: 4 }
    ];
    for (const rel of relationshipsData) {
      if (!p[rel.p1] || !p[rel.p2]) continue;
      await PersonRelationship.create({ personId1: p[rel.p1].id, personId2: p[rel.p2].id, relationshipTypeId: rel.type });
    }
    console.log(`-> 已创建 ${relationshipsData.length} 条关系`);
    const eventsData = [
      { personId: p[7].id, eventTypeId: 1, eventTime: '1994-05-20', description: '与李丽结婚' },
      { personId: p[14].id, eventTypeId: 6, eventTime: '2013-09-01', description: '考入北京大学' },
      { personId: p[3].id, eventTypeId: 2, eventTime: '1980-01-01', description: '晋升为车间主任' },
    ];
    await PersonEvent.bulkCreate(eventsData);
    console.log(`-> 已创建 ${eventsData.length} 条事件`);
    console.log('✅ 数据库初始化和数据填充完成！');
  } catch (error) {
    console.error('❌ 数据库初始化失败:', error);
    throw error;
  }
}

// 如果直接从命令行运行此文件
if (import.meta.url === `file://${process.argv[1]}`) {
  initializeDatabase()
    .then(() => {
      console.log('脚本执行成功！');
      process.exit(0);
    })
    .catch(error => {
      console.error('脚本执行遇到错误:', error);
      process.exit(1);
    });
} 